define(function(require, exports) {
	var util = require('util');
	var pubjs = require('pubjs');
	var view = require('@base/view');
	var $ = require('jquery');
	var Tab = require('@base/common/base').tab;


	// 模块层级说明：
	// 1、首先由layout模块布局
	// 2、layout下由不同类型的block构建块样式及块容器
	// 3、 block下才是具体的chart模块
	var NestLayout = require('modules/nestLayout').base;

	// 默认昨天
	var DEFAULT_DATE = new Date();
	DEFAULT_DATE = DEFAULT_DATE.setDate(DEFAULT_DATE.getDate() -1);
	DEFAULT_DATE = new Date(DEFAULT_DATE);

	var Base = view.container.extend({
		init: function(config)
		{
			config = pubjs.conf(config, {
				class: 'M-HomeDashboard',
				// 布局模块和布局模块配置, 可以是单个布局，也可多个布局, 配置分别为对象或者数组
				layout: {
					config: {}
				},
				/**
				 * 模块配置
				 * eg:
				 *	{
				 *		// 模块名称，如果没传，则默认为target
				 *		name: '',
				 *		// layout中的容器名称
				 *		target: '',
				 *		// 模块uri
				 *		module: '',
				 *		// 模块配置
				 *		config: {}
				 *	}
				 */
				blocks: []
			});

			this.$prefix = '_HOME_DASHBOARD_BLOCK_';

			// 默认配置
			this.$param = {
				time_range: 1,
				start: util.date('Ymd', DEFAULT_DATE),
				end: util.date('Ymd', DEFAULT_DATE)
			}

			this.Super('init', arguments);
		},
		afterBuild: function()
		{
			var c = this.getConfig();
			var el = this.getDOM();
			this.buildFromTemplate({});

			var layout = c.layout;
			if (!util.isArray(layout))
			{
				layout = [layout];
			}

			util.each(layout, function(item, index)
			{
				var mod = this.create('layout_' + index, NestLayout, util.extend({
					target: this.getContainer()
				}, item.config));
				this.createBlocks(mod);
			}, this);
		},
		createBlocks: function(mod)
		{
			var c = this.getConfig();
			var list = [];
			util.each(c.blocks, function(item)
			{
				var target = mod.getContainer(item.target);
				if (!target)
				{
					return ;
				}
				list.push([
					this.$prefix + (item.name || item.target),
					item.module,
					util.extend({target: target}, item.config)
				]);
			}, this);

			this.createAsyncArray(list, this.load);
		},
		getBlock: function(name)
		{
			return this.$[this.$prefix + name];
		},
		load: function()
		{
			var blocks = this.getConfig('blocks');
			var campaign_id = this.getConfig('campaign_id');
			// 如果没有时间设置，默认今天
			var start = this.$param.start || util.date('Ymd', DEFAULT_DATE);
			var end = this.$param.end || util.date('Ymd', DEFAULT_DATE);
			var time_range = this.$param.time_range || 1;

			// 测试写死一个活动id数据
			// var campaign_id = 83;
			util.each(blocks, function(item)
			{
				var name = item.name || item.target;
				var block = this.getBlock(name);
				if (!block)
				{
					return ;
				}
				block.setParam({
					'campaign_id': campaign_id,
					'start': start,
					'end': end,
					'time_range': time_range
				}).reset().load();
			}, this);
		},
		setParam: function(param)
		{
			this.$param = util.extend({}, this.$param, param);
			return this;
		}
	});
	exports.base = Base;

	var Main = view.container.extend({
		init: function(config){
			var param = config.param;
			var campaign_id;
			if (param.condition)
			{
				var condition = JSON.parse(param.condition);
				util.each(condition, function(item)
				{
					if (item.campaign_id)
					{
						campaign_id = item.campaign_id;
					}
				});
			}

			config = pubjs.conf(config, {
				class: 'pr',
				campaign_id: campaign_id,
				uuid: util.uuid(),
				view_model: {
					eventChangeType: this.eventChangeType
				}
			});

			// 默认选择按1天查看
			this.$time_range = 1;

			this.Super('init', arguments);
		},
		afterBuild: function()
		{
			var c = this.getConfig();
			var el = this.getDOM();

			$([
				'<div class="dateCon">',
					'<span class="day1 mr10 pd5" ms-click="eventChangeType(1)">' + LANG('按1天查看')+ '</span>',
					'<span class="day7 mr10 pd5" ms-click="eventChangeType(7)">' + LANG('按7天查看') + '</span>',
					'<span pub-name="people_date" pub-mod="@base/common/date.dateRangeNew"></span>',
				'</div>',
				'<div class="tabCon" pub-name="tab" pub-mod="@base/common/base.tab"></div>'
			].join('')).appendTo(el);

			el.find('.dateCon').css({'position': 'absolute', 'right': 0, 'z-index': 1});
			el.find('.tabCon').css({'position': 'relative', 'top': '10px'});
			this.$day1 = el.find('.day1').css('background', '#e7e7e7');
			this.$day7 = el.find('.day7');

			this.buildFromTemplate({
				'people_date': {
					'buttons': null,
					'userStorage': false,
					'broadcast': false,
					// 'prevBtn': null,
					// 'nextBtn': null,
					'pos': 'bR',
					'begin': DEFAULT_DATE,
					'end': DEFAULT_DATE
				},
				'tab': {
					'async': true,
					'silent': false,
					'list': {
						'overview': {
							text: LANG('人群概览'),
							module: 'subgrid/people.overview',
							config: {
								'campaign_id': c.campaign_id
							}
						},
						'spot': {
							text: LANG('广告情况'),
							module: 'subgrid/people.spot',
							config: {
								'campaign_id': c.campaign_id
							}
						}
					},
					'uuid': util.uuid()
				}
			});
		},
		onDateRangeChange: function(ev)
		{
			if (ev.name == 'people_date')
			{
				this.changeDate();
			}
		},
		changeDate: function()
		{
			var time_range = +this.$time_range;
			var date = this.$.people_date.getData(true);

			// 选择查看1天的时间
			if (time_range == 1)
			{
				// 如果选择一天，开始和结束时间要一致
				if (date.begin != date.end)
				{
					pubjs.alert(LANG('请选择1天的时间'));
					return false;
				}
			}

			// 选择查看7天的时间
			if (time_range == 7)
			{
				if ((date.end - date.begin) != (6 * 24 * 60 * 60))
				{
					pubjs.alert(LANG('请选择7天的时间'));
					return false;
				}
			}
			this.reload();
		},
		eventChangeType: function(type)
		{
			this.$time_range = +type;
			var date = new Date(DEFAULT_DATE);
			var end = util.date('Ymd', date);
			var begin = util.date('Ymd', date);

			if (type == 1)
			{
				this.$day1.css('background', '#e7e7e7');
				this.$day7.css('background', '');
			}

			if (type == 7)
			{
				this.$day1.css('background', '');
				this.$day7.css('background', '#e7e7e7');
				date.setDate(date.getDate() - 6);
				begin = util.date('Ymd', date);
			}

			this.$.people_date.setData({
				begin: begin,
				end: end
			});

			this.reload();
		},
		reload: function()
		{
			var date = this.$.people_date.getData(true);
			this.$.tab.setParam({
				'start': date.begin,
				'end': date.end,
				'time_range': this.$time_range
			});
		}
	});
	exports.main = Main;

	// 区块间距
	var BLOCK_ITEM_PADDING = 25;
	var METRICS = [
		// {
		// 	field: 'impressions',
		// 	text: LANG('展示量')
		// },
		// {
		// 	field: 'clicks',
		// 	text: LANG('点击量'),
		// 	yAxisIndex: 1
		// },
		{
			field: 'value',
			text: LANG('访客数')
		}
	];

	var DEFAULT_PARAM = {
		"metrics": ["impressions"],
		"sort": "impressions|-1"
	};

	var DEFAULT_YFIELD = [
		{
			field: 'impressions'  // Y轴字段名称
			,yAxisIndex: 0 // 字段Y轴索引
			,text: null     // Y轴label
			,format: null   // Y轴格式化函数
		}
	];

	var Overview = Base.extend({
		init: function(config)
		{
			config = pubjs.conf(config, {
				layout: {
					config: {
						dir: 'H',
						padding: BLOCK_ITEM_PADDING,
						css: {
							'margin-top': BLOCK_ITEM_PADDING
						},
						items: [
							{
							name: 'left',
								width: '32.5%',
								dir: 'V',
								padding: BLOCK_ITEM_PADDING,
								items: [
									'gender(&360)',
									'career(&360)'
								]
							},
							{
								name: 'middle',
								width: '32.5%',
								dir: 'V',
								padding: BLOCK_ITEM_PADDING,
								items: [
									'age(&360)',
									'system'
								]
							},
							{
								name: 'right',
								width: 'auto',
								dir: 'V',
								padding: BLOCK_ITEM_PADDING,
								items: [
									'interest(&360)',
									'area'
								]

							}
						]
					}
				},
				blocks: [
					{
						target: 'gender',
						module: 'modules/dashboard/block.normal',
						config: {
							title: LANG("性别"),
							color: '#66D99F',
							configTransfer: {
								color: false
							},
							url: 'peopleGrid/sex',
							module: 'modules/dashboard/pie.dountDouble'
						}
					},
					{
						target: 'age',
						module: 'modules/dashboard/block.normal',
						config: {
							title: LANG("年龄"),
							color: '#66D99F',
							url: 'peopleGrid/age',
							module: 'modules/dashboard/bar.oneMetric',
							config: {
								build: {
									grid: {
										x: 40
									},
									yAxis: {
										axisLabel: {
											formatter: '{value} %'
										},
										axisLine: {
											show: false
										}
									}
								},
								dataProcess: function(items)
								{
									var total = 0;
									var list = [];
									util.each(items, function(item)
									{
										total += item.value || 0;
									});
									util.each(items, function(item)
									{
										list.push({
											name: item.name || '',
											value: util.toFixed(item.value / total * 100, 1)
										})
									});
									return list;
								}
							}
						}
					},
					{
						target: 'career',
						module: 'modules/dashboard/block.normal',
						config: {
							title: LANG("所在行业"),
							color: '#66D99F',
							configTransfer: {
								color: false
							},
							url: 'peopleGrid/industry',
							module: 'modules/dashboard/pie.rose'
						}
					},
					{
						target: 'interest',
						module: 'modules/dashboard/block.normal',
						config: {
							title: LANG("兴趣爱好"),
							color: '#66D99F',
							configTransfer: {
								color: false
							},
							url: 'peopleGrid/hobby',
							module: 'modules/dashboard/treemap.main'
						}
					},
					{
						target: 'system',
						module: 'modules/dashboard/block.hasSwitch',
						config: {
							title: LANG("操作系统"),
							module: 'modules/dashboard/horizontalBar.base',
							url: 'peopleGrid/os',
							metrics: METRICS,
							config: {
								xField: 'name',
								yField: {
									format: function(item) {
										return util.numberFormat(item);
									}
								}
							}
						}
					},
					{
						target: 'area',
						module: 'modules/dashboard/block.hasSwitch',
						config: {
							title: LANG("展示地区TOP10"),
							module: 'modules/dashboard/horizontalBar.base',
							url: 'peopleGrid/region',
							metrics: METRICS,
							config: {
								xField: 'name',
								yField: {
									format: function(item) {
										return util.numberFormat(item);
									}
								}
							}
						}
					}
				]
			});

			this.$prefix = '_HOME_DASHBOARD_BLOCK_';
			this.Super('init', arguments);
		}
	});

	exports.overview = Overview;


	var SPOT_METRIC = [
		{
			field: 'clicks',
			text: LANG('点击量')
		},
		{
			field: 'ctr',
			text: LANG('CTR'),
			formatter: '{value} %'
		}
	];
	var SPOT_YFIELD = [
		{
			field: 'impressions'        // 值字段名
			,text: '展示量'            // Y轴label
			,format: null         // 值字段格式化函数
			,type: 'bar'
		},
		{
			field: 'crt'        // 值字段名
			,text: '点击率'            // Y轴label
			// 值字段格式化函数
			,format: null
			,type: 'line'
			,yAxisIndex: 1
		}
	];
	var Spot = Base.extend({
		init: function(config)
		{
			config = pubjs.conf(config, {
				layout: [
				{
					config: {
						dir: 'H',
						padding: BLOCK_ITEM_PADDING,
						css: {
							'margin-top': BLOCK_ITEM_PADDING
						},
						items: [
							{
								name: 'left_1',
								width: '32.5%',
								dir: 'V',
								padding: BLOCK_ITEM_PADDING,
								items: [
									// 性别
									'sex(&360)',
									// 地域
									'region(&360)'
								]
							},
							{
								name: 'right_1',
								width: 'auto',
								dir: 'V',
								padding: BLOCK_ITEM_PADDING,
								items: [
									// 年龄分布
									'age(&360)',
									// 行业
									'industry(&360)'
								]
							}
						]
					}
				},
				{
					config: {
						dir: 'H',
						padding: BLOCK_ITEM_PADDING,
						css: {
							'margin-top': BLOCK_ITEM_PADDING
						},
						items: [
							{
								name: 'left_2',
								width: 'auto',
								dir: 'V',
								padding: BLOCK_ITEM_PADDING,
								items: [
									'interest(&360)'
								]
							},
							{
								name: 'right_2',
								width: '32.5%',
								dir: 'V',
								padding: BLOCK_ITEM_PADDING,
								items: [
									'os(&360)'
								]
							}
						]
					}
				}],
				blocks: [
					{
						target: 'sex',
						module: 'modules/dashboard/block.hasSwitchLineBar',
						config: {
							title: LANG("性别"),
							color: '#66D99F',
							metrics: SPOT_METRIC,
							config: {
								color: ['#eaedf2', '#d59fe0'],
								yField: SPOT_YFIELD
							},
							url: 'peopleGrid/ctr_sex',
							module: 'modules/dashboard/lineBar.base'
						}
					},
					{
						target: 'region',
						module: 'modules/dashboard/block.hasSwitchLineBar',
						config: {
							title: LANG("地域分布"),
							color: '#66D99F',
							metrics: SPOT_METRIC,
							defaultSort: 'impressions|-1',
							param: {limit: 5},
							config: {
								color: ['#eaedf2', '#66d99f'],
								yField: SPOT_YFIELD,
								build: {
									grid: {
										y2: 80
									},
									xAxis: {
										axisLabel: {
											interval: 0,
											rotate:45
										}
									}
								}
							},
							url: 'peopleGrid/ctr_region',
							module: 'modules/dashboard/lineBar.base'
						}
					},
					{
						target: 'age',
						module: 'modules/dashboard/block.hasSwitchLineBar',
						config: {
							title: LANG("年龄"),
							color: '#66D99F',
							metrics: SPOT_METRIC,
							config: {
								color: ['#eaedf2', '#3ec7ee'],
								yField: SPOT_YFIELD
							},
							url: 'peopleGrid/ctr_age',
							module: 'modules/dashboard/lineBar.base'
						}
					},
					{
						target: 'industry',
						module: 'modules/dashboard/block.hasSwitchLineBar',
						config: {
							title: LANG("行业分布"),
							color: '#66D99F',
							metrics: SPOT_METRIC,
							config: {
								color: ['#eaedf2', '#f98c33'],
								yField: SPOT_YFIELD
							},
							url: 'peopleGrid/ctr_industry',
							module: 'modules/dashboard/lineBar.base'
						}
					},
					{
						target: 'interest',
						module: 'modules/dashboard/block.hasSwitchLineBar',
						config: {
							title: LANG("兴趣爱好"),
							color: '#66D99F',
							metrics: SPOT_METRIC,
							defaultSort: 'impressions|-1',
							config: {
								color: ['#eaedf2', '#f15556'],
								yField: SPOT_YFIELD
							},
							url: 'peopleGrid/ctr_hobby',
							module: 'modules/dashboard/lineBar.base'
						}
					},
					{
						target: 'os',
						module: 'modules/dashboard/block.hasSwitchLineBar',
						config: {
							title: LANG("操作系统"),
							color: '#66D99F',
							metrics: SPOT_METRIC,
							defaultSort: 'impressions|-1',
							param: {limit: 5},
							config: {
								color: ['#eaedf2', '#83be56'],
								yField: SPOT_YFIELD,
								build: {
									grid: {
										y2: 100
									},
									xAxis: {
										axisLabel: {
											interval: 0,
											rotate: 30
										}
									}
								}
							},
							url: 'peopleGrid/ctr_os',
							module: 'modules/dashboard/lineBar.base'
						}
					}
				]
			});

			this.$prefix = '_HOME_DASHBOARD_BLOCK_';
			this.Super('init', arguments);
		}
	});

	exports.spot = Spot;
});